package com.lm.curator.example;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;

public class LeaderElectionExample {
    public static void main(String[] args) throws InterruptedException {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        client.start();

        // 创建 LeaderSelector
        LeaderSelector leaderSelector = new LeaderSelector(client, "/leader-election", new LeaderSelectorListenerAdapter() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                System.out.println("成为 Leader，执行任务...");
                Thread.sleep(3000); // 模拟任务
                System.out.println("任务完成，释放 Leader 权限");
            }
        });

        leaderSelector.autoRequeue(); // 自动重新排队参与选举
        leaderSelector.start();

        Thread.sleep(Integer.MAX_VALUE); // 保持主线程运行
        client.close();
    }
}
